package com.zut.chat.controller;

import com.zut.chat.entity.User;
import com.zut.chat.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 会话管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/session")
@CrossOrigin(origins = "*")
public class SessionController {

    @Autowired
    private UserService userService;

    /**
     * 验证会话是否有效
     */
    @GetMapping("/validate")
    public ResponseEntity<?> validateSession(@RequestParam String sessionId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            User user = userService.findBySessionId(sessionId);
            
            if (user != null) {
                response.put("success", true);
                response.put("valid", true);
                response.put("nickname", user.getNickname());
                response.put("userType", user.getUserType().name());
                response.put("message", "会话有效");
                
                log.info("会话验证成功: {} - {}", sessionId, user.getNickname());
            } else {
                response.put("success", true);
                response.put("valid", false);
                response.put("message", "会话无效或已过期");
                
                log.warn("会话验证失败: {} - 用户不存在", sessionId);
            }
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("会话验证异常: {}", sessionId, e);
            response.put("success", false);
            response.put("message", "验证会话时发生错误");
            return ResponseEntity.status(500).body(response);
        }
    }
} 